#include "udp.h"
#include <ctype.h>
#include <time.h>

void SaveRecord(const char *word, const char *buf);
/* 其他必要的环境已封装好了，只需要实现与客户端的交互即可
 * 这里的fd是服务端的socket，
 * addr是服务端的地址*/
void udp_main(const int fd, const char *argv) {
    char buf[BUFSIZ] = {}, word[128] = {};
    send(fd, argv, strlen(argv)+1, 0);
    int i;
    for(i = 0; isalpha(argv[i]) || argv[i] == ' '; i++)
        word[i] = argv[i];
    word[i] = '\0';
    recv(fd, buf, BUFSIZ, 0);
    if(buf[strlen(buf) - 1] == '\n')
        buf[strlen(buf) - 1] = '\0';
    printf("buf=%s\n", buf);
    SaveRecord(word, buf);
}

void SaveRecord(const char *word, const char *buf) {
    FILE *fp;
    time_t ctime;
    struct tm *ctimestr;
    int linecount = 0;
    char str[128] = {};
    if( (fp = fopen("recode.txt", "a+") ) == NULL)
        ErrExit("fopen");
    while( fgets(str, 128, fp) != NULL) {
        if(str[strlen(str) - 1] == '\n') {
            linecount++;
        }
    }
    ctime = time(NULL);
    ctimestr = localtime(&ctime);
    printf("%d\t%04d-%02d-%02d %02d:%02d:%02d\t%s\t%s\n",
            linecount,
            ctimestr->tm_year+1900, ctimestr->tm_mon+1, ctimestr->tm_mday,
            ctimestr->tm_hour, ctimestr->tm_min, ctimestr->tm_sec, word, buf);
    fprintf(fp, "%d\t%04d-%02d-%02d %02d:%02d:%02d\t%s\t%s\n",
            linecount,
            ctimestr->tm_year+1900, ctimestr->tm_mon+1, ctimestr->tm_mday,
            ctimestr->tm_hour, ctimestr->tm_min, ctimestr->tm_sec, word, buf);
    linecount++;
    fclose(fp);
}